package in.rinisoft.sonar.maven.plugin;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.codehaus.plexus.util.IOUtil;

/**
 * Code has been taken from Codehaus Sonar plugin and modified to suit the
 * needed whereever needed
 * 
 * @author Neeraj Mittal 
 */
public class ServerMetadata {
	public static final int CONNECT_TIMEOUT_MILLISECONDS = 30000;
	public static final int READ_TIMEOUT_MILLISECONDS = 60000;
	private String url;
	private String version;

	public ServerMetadata(String url) {
		if (url.endsWith("/")) {
			this.url = url.substring(0, url.length() - 1);
		} else {
			this.url = url;
		}
	}

	public String getVersion() throws IOException {
		if (this.version == null) {
			this.version = remoteContent("/api/server/version");
		}
		return this.version;
	}

	public String getUrl() {
		return this.url;
	}

	public void logSettings(Log log) throws MojoExecutionException {
		try {
			log.info("Sonar version: " + getVersion());
		} catch (IOException e) {
			throw new MojoExecutionException(
					"Sonar server can not be reached at " + this.url
							+ ". Please check the parameter 'sonar.host.url'.");
		}
	}

	protected String remoteContent(String path) throws IOException {
		String fullUrl = this.url + path;
		HttpURLConnection conn = getConnection(fullUrl, "GET");
		InputStream input = (InputStream) conn.getContent();
		try {
			int statusCode = conn.getResponseCode();
			if (statusCode != 200) {
				throw new IOException("Status returned by url : '" + fullUrl
						+ "' is invalid : " + statusCode);
			}
			return IOUtil.toString(input);
		} finally {
			IOUtil.close(input);
			conn.disconnect();
		}
	}

	static HttpURLConnection getConnection(String url, String method)
			throws IOException {
		URL page = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) page.openConnection();
		conn.setConnectTimeout(30000);
		conn.setReadTimeout(60000);
		conn.setRequestMethod(method);
		conn.connect();
		return conn;
	}

	protected boolean supportsMaven3() throws IOException {
		return !isVersionPriorTo2Dot4(getVersion());
	}

	protected static boolean isVersionPriorTo2Dot4(String version) {
		return (version.startsWith("1.")) || (version.startsWith("2.0."))
				|| (version.equals("2.1")) || (version.equals("2.2"))
				|| (version.startsWith("2.1.")) || (version.startsWith("2.3."))
				|| (version.equals("2.3"));
	}
}